#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/9 12:42
# @Author  : 李中华
# @Email   : 1260429766@qq.com
# @File    : runAll.py
import os
from ProjectPath import projectPath
import unittest
from common.HTMLTestRunner import HTMLTestRunner
from common import configEmail
from common.readConfig import ReadConfig

reportFileName = '接口自动化测试报告.html'
readConfig = ReadConfig()
class AllTest:
    def __init__(self):
        self.caseListPath = os.path.join(projectPath,'config','caselist.txt')
        self.caseDir = os.path.join(projectPath,'testcase')
        self.reportFile = os.path.join(projectPath,'resultreport',reportFileName)
        self.caseList = []

    def getCaseList(self):
        with open(file=self.caseListPath,mode='r',encoding='utf-8') as f:
            for readline in f.readlines():
                if readline.startswith('#'):
                    pass
                else:
                    self.caseList.append(str(readline).replace('\n',''))

    def getCaseSuite(self):
        self.getCaseList()
        testSuite = unittest.TestSuite()
        suitemodule = []
        for caseList in self.caseList:
            print(self.caseDir)
            print(caseList.split('/')[-1] + '.py')
            discover = unittest.defaultTestLoader.discover(self.caseDir,pattern=caseList.split('/')[-1] + '.py',top_level_dir=None)
            suitemodule.append(discover)
        if len(suitemodule) > 0:
            for suite in suitemodule:
                for suite_name in suite:
                    testSuite.addTest(suite_name)
        else:
            print('else:')
            return None
        return testSuite

    def runner(self):
        try:
            suite = self.getCaseSuite()
            if suite is not None:
                report = open(self.reportFile,'wb')
                html = HTMLTestRunner(stream=report, title=u'测试报告', description='眸视科技web接口测试报告', tester='李中华')
                html.run(suite)
                report.close()
            else:
                print("测试用例为空")
        except Exception as e:
            print(e)
        if readConfig.get_email('on_off') == 'on':
            configEmail.send_email(reportFileName)
        else:
            pass

if __name__ == '__main__':
    AllTest().runner()